layui.use(['form', 'layer', 'laydate', 'table', 'laytpl'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laydate = layui.laydate,
        laytpl = layui.laytpl,
        table = layui.table;

    //文章列表
    var tableIns = table.render({
        elem: '#articalList',
        url: '/manage/artical/data',
        cellMinWidth: 95,
        page: true,
        height: "full-125",
        limit: 10,
        limits: [10, 15, 20, 25],
        id: "articalListTable",
        cols: [[
            {type: "checkbox", fixed: "left", width: 50},
            {field: 'id', title: '编号', align: "center"},
            {field: 'title', title: '文章标题', align: "left"},
            {field: 'createname', title: '发布者', align: 'center'},
            {field: 'type', title: '分类', align: 'left'},
            {
                field: 'showflag', title: '是否公开', align: 'center',
                templet: function (d) {
                    return '<input type="checkbox" name="showflag" lay-filter="showflag" lay-skin="switch" switch_id="' + d.id + '" lay-text="是|否" ' + d.showflag + '>'
                }
            },
            {field: 'createtime', title: '创建时间', align: 'center'},
            {title: '操作', width: 170, templet: '#articalListBar', fixed: "right", align: "center"}
        ]]
    });

    //是否公开
    form.on('switch(showflag)', function (data) {
        var index = layer.msg('修改中，请稍候', {icon: 16, time: false, shade: 0.8});
        setTimeout(function () {
            layer.close(index);
            //自定义switch_id 作为主键 用作修改内容唯一标识
            var id = data.elem.attributes['switch_id'].nodeValue;
            $.ajax({
                //几个参数需要注意一下
                type: "POST",//方法类型
                dataType: "json",//预期服务器返回的数据类型
                url: "/manage/artical/show",//url
                data: {
                    id: id,
                },
                success: function (result) {
                    layer.msg("设置成功！", {icon: 1});
                }, error: function () {
                    layer.msg("操作失败，请重试！", {icon: 2});
                }
            });
        }, 500);
    });

    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】
    $(".search_btn").on("click", function () {
        if ($(".searchVal").val() != '') {
            table.reload("articalListTable", {
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    key: $(".searchVal").val()  //搜索的关键字
                }
            })
        } else {
            layer.msg("请输入搜索的内容", {icon: 7});
        }
    });

    //添加文章
    function addArtical() {
        var index = layui.layer.open({
            title: "添加文章",
            type: 2,
            content: "/manage/artical/add",
            success: function (layero, index) {
                var body = layui.layer.getChildFrame('body', index);
                setTimeout(function () {
                    layui.layer.tips('点击此处返回列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                }, 500)
            }
        });
        layui.layer.full(index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize", function () {
            layui.layer.full(index);
        })
    }

    function updateArtical(data) {
        var index = layui.layer.open({
            title: "修改文章",
            type: 2,
            content: "/manage/artical/update?id=" + data.id,
            success: function (layero, index) {
                var body = layui.layer.getChildFrame('body', index);
                setTimeout(function () {
                    layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                }, 500)
            }
        });
        layui.layer.full(index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize", function () {
            layui.layer.full(index);
        })
    }

    $(".add_btn").click(function () {
        addArtical();
    });

    //批量删除
    $(".deleteBatch_btn").click(function () {
        var checkStatus = table.checkStatus('articalListTable'),
            data = checkStatus.data,
            ids = [];
        if (data.length > 0) {
            for (var i in data) {
                ids.push(data[i].id);
            }
            layer.confirm('确定删除选中的文章？', {icon: 3, title: '提示信息'}, function (index) {
                $.ajax({
                    url: "/manage/artical/deleteBatch",
                    type: "POST",
                    dataType: "json",//预期服务器返回的数据类型
                    data: {
                        "ids": ids,
                    },
                    traditional: true,//这里设置为true 否则后台接受会报错
                    success: function (result) {
                        if (result.flag == "success") {
                            top.layer.msg("批量删除成功！", {icon: 1});
                        } else {

                        }
                        tableIns.reload();
                        layer.close(index);
                    }, error: function () {
                        layer.msg("批量删除失败", {icon: 2});
                    }
                });

            })
        } else {
            layer.msg("请选择需要删除的文章", {icon: 7});
        }
    });


    //编辑文章内容
    $(".edit_btn").click(function () {
        var checkStatus = table.checkStatus('articalListTable'),
            data = checkStatus.data;
        if (data.length == 1) {
            var id = data[0].id;
            var win = window.open();
            $.ajax({
                url: '/manage/artical/edit',
                type: 'post',
                data: {
                    id: id
                },
                asyn: false
            }).done(function (data) {
                var doc = win.document;
                doc.write(data);    // !!! 关键，接收后端的数据并进行新窗口写入
                doc.close();
            });


        } else if (data.length > 1) {
            layer.msg("只能选择一篇文章进行内容编辑，请重新选择！", {icon: 7});
        } else {
            layer.msg("请勾选一条需要编辑的文章！", {icon: 7});
        }
    });

    //列表操作
    table.on('tool(articalList)', function (obj) {
        var layEvent = obj.event,
            data = obj.data;

        if (layEvent === 'edit') { //编辑
            updateArtical(data);
        } else if (layEvent === 'del') { //删除
            layer.confirm('确定删除此文章？', {icon: 3, title: '提示信息'}, function (index) {
                $.post("/manage/artical/delete", {
                    id: data.id  //将需要删除的newsId作为参数传入
                }, function (data) {
                    data = JSON.parse(data);
                    if (data.flag === "success") {
                        layer.msg("删除成功", {icon: 1});
                        tableIns.reload();
                        layer.close(index);
                    } else {
                        layer.msg("删除失败！", {icon: 2});
                    }

                })
            });
        } else if (layEvent === 'look') { //预览
            layer.alert("此功能需要前台展示，实际开发中传入对应的必要参数进行文章内容页面访问")
        }
    });

});